<?php

class TemplateController extends BackOfficeController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
        $this->actionUpdate();
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
        //go to from page
        $page = null;
        if ($pageId = $this->get('page_id', 0))
        {
            $result = FSM::run('Cms.Page.get', array('id'=>$pageId));
            if (!$result->hasErrors())
            {
                $page = $result->model;
            }
        }
        
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax','') == 'template-form');
            if (is_object($page))
            {
                $_POST['page_id'] = $page->id;
                $_POST['page_revision'] = $this->get('page_revision', 0);
            }
            
            $str = $this->post('containers','');
            $str = substr($str, 1);
            $str = html_entity_decode($str);            
            $str = urldecode($str);
            parse_str($str, $containers);
            //new template revision
            //copy widgets and update page_widget_id in containers
            $_POST['containers'] = $containers;
            
            $result = FSM::run('Cms.Template.save', $_POST);
            $model = $result->model;
            if ($this->post('ajax','') == 'template-form'){
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }
            
            if (!$result->hasErrors())
            {
            	$this->message = Yii::t('Core','Item has been saved successfully.');
                
                //update position containers
                $containers = $result->containers;
                FSM::run('Cms.pageWidget.updateContainers', array(
                    'template_content_id'=>$model->currentRevision->id,
                    'containers'=>$containers,
                ));
                
                $params = array('id' => $model->id, 'revision_id' => $model->currentRevision->revision_id);
                if ($layout = Yii::app()->request->getParam('layout', false))
                    $params['layout'] = $layout;
                if (is_object($page))
                {
                    $params['page_id'] = $page->id;
                    $params['page_revision'] = $this->get('page_revision', 0);
                }
                $this->redirect($this->createUrl('update',$params));
            }
            else
                $revisionId = $model->currentRevision->revision_id;
        } else {
            // show edit form
            $id = $this->get('id', 0);
            $revisionId = $this->get('revision_id', 1);
            if ($id == 0) {
                $model = new Template();
                $model->currentRevision = new TemplateContent();
                $model->currentRevision->js_files = array('');
                $model->currentRevision->css_files = array('');
            } else {
                $model = FSM::run('Cms.Template.get', array('id' => $id, 'revision_id'=>$revisionId))->model;
            }
        }
        
        //fix init select files
        if ((isset($model) && is_object($model)) === false)
        {
            $this->redirect(array('create'));
        }
        if (!count($model->currentRevision->js_files))
            $model->currentRevision->js_files = array('');
        if (!count($model->currentRevision->css_files))
            $model->currentRevision->css_files = array('');
        
        $revisions = array();
        $containers = array();
        $pages = array();
        if ($model->id)
        {
            $revisions = FSM::run('Cms.templateContent.getRevisions', array(
                'template_id'=>$model->id
            ))->items;
            $models = FSM::run('Cms.page.usedInTemplate', array(
                'template_id'=>$model->id,
                'revision_id'=>($revisionId ? $revisionId : 1)
            ))->data;
            foreach ($models as $items)
            {
                $pages[] = array(
                    'label'=>(is_object($items->site) ? $items->site->name.' - ' : '').$items->title,
                    'url'=>array('/Cms/admin/page/update', 'id'=>$items->id),
                );
            }
            //detect containers
            $result = FSM::run('Cms.templateContent.findAllContainters', array('id'=>(is_object($model->currentRevision) ? $model->currentRevision->id : 0)));
            if (! $result->hasErrors())
            {
                $containers = $result->containers;
            }
            //load widgets
            $widgets = FSM::_run('Cms.templateContent.getAllWidgets', array('id'=>$model->currentRevision->id))->data;
            $containers = CMap::mergeArray($containers, $widgets);
        }
        
        $childrenTemplates = FSM::_run('Cms.templateContent.getChildrenTemplate', array(
            'id'=>(is_object($model->currentRevision) ? $model->currentRevision->id : 0
        )))->children;
        
        $this->render('update', array(
            'model' => $model,
            'revisions'=>$revisions,
            'page'=>$page,
            'pages'=>$pages,
            'containers'=>$containers,
            'childrenTemplates'=>$childrenTemplates,
        ));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            if (($id = $this->get('id',null)) !== null) {
                $ids = is_numeric($id) ? array($id) : explode(',',$id);
                
                // delete one or multiple objects given the list of object IDs
                $result = FSM::run('Cms.Template.delete', array('ids' => $ids));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif(!Yii::app()->request->isAjaxRequest) {
                    // only redirect user to the admin page if it is not an AJAX request
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400,Yii::t('Core','Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400,Yii::t('Core','Invalid request. Please do not repeat this request again.'));
        }
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $this->actionAdmin();
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
        $model=new Template('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Template']))
            $model->attributes=$_GET['Template'];

        $this->render('admin',array(
            'model'=>$model,
        ));
	}
    
    public function actionStatus()
    {
        $result = FSM::run('Cms.Template.changeStatus', $_GET);
        if ($result->hasErrors()) {
            echo $result->getError('ErrorCode');
        } elseif(!Yii::app()->request->isAjaxRequest) {
            // only redirect user to the admin page if it is not an AJAX request
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
    }
    
    public function actionUnused()
    {
        $model=new Template('unused');
        $model->unsetAttributes();
        
        if(isset($_GET['Template']))
            $model->attributes=$_GET['Template'];
            
        $this->render('unused', array('model'=>$model));
    }
    
    public function actionRemoveRevision()
    {
        $templateId = $this->get('id', 0);
        $revision = $this->get('revision', 0);
        
        $criteria = new CDbCriteria();
        $criteria->compare('template_id', $templateId);
        $criteria->compare('revision_id', $revision);
        $templateContent = TemplateContent::model()->find($criteria);
        if (is_object($templateContent))
        {
            $criteria = new CDbCriteria();
            $criteria->compare('template_content_id', $templateContent->id);
            if (! PageRevision::model()->exists($criteria))
            {
                //remove widgets added to template
                PageWidget::model()->deleteAllByAttributes(array('template_content_id'=>$templateContent->id));
                $templateContent->delete();
                echo Yii::t('Core','Item has been deleted successfully.');
            }
            else
            {
                echo Yii::t('Core',"Can't delete this template revision. Some page is using it.");
            }
        }
        else
        {
            echo Yii::t('Core','Template content not exist.');
        }
    }
    
    public function actionLayouts()
    {
        $container = Yii::app()->request->getParam('container', '');
        $pageId = Yii::app()->request->getParam('page_id', 0);
        $revisionId = Yii::app()->request->getParam('revision_id', 0);
        $width = $this->get('width', 960);
        $model = new Layout;
        
        //save data
        if (isset($_POST['Layout']))
        {
            $id = (int) $_POST['Layout']['id'];
            $model->unsetAttributes();
            if(isset($_POST['Layout']))
            {
                if ($id < 0)
                    unset($_POST['Layout']['id']);
                $model->attributes=$_POST['Layout'];
            }
            parse_str(urldecode($model->data), $data);
            $model->data = $data['data'];
            $model->data = serialize($model->data);
            if ($id)
            {
                $model->id = $id;
                $model->setIsNewRecord(false);
            }
            if ($model->save())
            {
                echo CJSON::encode(array('id'=>$model->id));
                $this->useLayout($container,$pageId,$revisionId,$model->id);
            }
            else
            {
                echo CJSON::encode(array('id'=>0,'error'=>$model->getErrors()));
            }
            Yii::app()->end();
        }
        
        $model->width = $width;
        $model->name = 'page_'.$pageId.'_revision_'.$revisionId.'_container_'.$container;
        $options=array(
            'layout_width'=>$model->width
        );
        
        $id=0;
        //update layout
        if (isset($_REQUEST['id']))
        {
            $id = (int) $_REQUEST['id'];
        }
        //load current layout of container
        elseif (!empty($container) && $pageId)
        {
            $layoutContainer = FSM::_run('Cms.LayoutContainer.find', array(
                'container'=>$container,
                'page_id'=>$pageId,
                'revision_id'=>$revisionId,
            ))->model;
            if (is_object($layoutContainer))
            {
                $id = $layoutContainer->layout_id;
            }
        }
        if ($id)
        {
            $model = Layout::model()->findByPk($id);
            if (is_object($model))
            {
                $options = array(
                    'layout_width'=>$model->width,
                    'data'=>unserialize($model->data)
                );
                $model->data = CJavaScript::encode($options['data']);
            }
            else
            {
                $model = new Layout;
                $model->name = 'page_'.$pageId.'_revision_'.$revisionId.'_container_'.$container;
                $model->width = $width;
            }
        }
//        CVarDumper::dump($model->data);exit;
        
        $criteria = new CDbCriteria;
        $criteria->order = 'name,id';
        $layouts = Layout::model()->findAll($criteria);
        if (count($layouts))
        {
            $layouts = CHtml::listData($layouts,'id','name');
        }
        $this->render('layouts', array(
            'layouts'=>$layouts,
            'options'=>$options,
            'model'=>$model,
            'container'=>$container,
            'pageId'=>$pageId,
            'revisionId'=>$revisionId,
        ));
    }
    
    protected function useLayout($container,$pageId,$revisionId, $layoutId,$remove=false)
    {
        /*$remove = (boolean) $this->get('remove', false);
        $container = $this->get('container', '');
        $pageId = $this->get('page_id', 0);
        $revisionId = $this->get('revision_id', 0);*/
        
        if ($remove)
        {
            FSM::_run('Cms.LayoutContainer.remove', array(
                'container'=>$container,
                'page_id'=>$pageId,
                'revision_id'=>$revisionId,
            ));
        }
        else
        {
            FSM::_run('Cms.LayoutContainer.update', array(
                'container'=>$container,
                'page_id'=>$pageId,
                'revision_id'=>$revisionId,
                'layout_id'=>$layoutId,
            ));
        }
    }
}